<template>
  <v-overlay :model-value="loading" persistent class="align-center justify-center">
    <v-progress-circular color="primary" size="64" indeterminate></v-progress-circular>
  </v-overlay>
  <VDialog :width="$vuetify.display.smAndDown ? 'auto' : 900" v-model="visible">
    <!-- Dialog close btn -->
    <DialogCloseBtn @click="visible = false" />
    <VCard title="上传元素图" >
      <VCardItem>
        <div class="flex">
          <div class="w-full h-auto relative">
            <div ref="dropZoneRef" class="cursor-pointer" @click="() => open()">
              <div v-if="fileData.length === 0" class="d-flex flex-column justify-center align-center gap-y-2 pa-12 drop-zone rounded">
                <IconBtn variant="tonal" class="rounded-sm">
                  <VIcon icon="tabler-upload" />
                </IconBtn>
                <h4 class="text-h4">
                  支持拖拽图片文件或者压缩包
                </h4>

              </div>

              <div v-else class="d-flex justify-center align-center gap-3 pa-8 drop-zone flex-wrap">
                <VRow class="match-height w-100">
                  <template v-for="(item, index) in fileData" :key="index">
                    <VCol cols="12" sm="4">
                      <VCard :ripple="false">
                        <VCardText class="d-flex flex-column" @click.stop>
                          <VImg v-if="item.file.type.includes('zip')" :src="ZipIcon" width="200px" height="150px" class="w-100 mx-auto" />
                          <VImg v-else-if="item.file.name.endsWith('.rar')" :src="RarIcon" width="200px" height="150px" class="w-100 mx-auto" />
                          <VImg v-else :src="item.url" width="200px" height="150px" class="w-100 mx-auto" />
                          <div class="mt-2">
                            <span class="clamp-text text-wrap">
                              {{ item.file.name }}
                            </span>
                            <span>
                              {{ item.file.size / 1000 }} KB
                            </span>
                          </div>
                        </VCardText>
                        <VCardActions>
                          <VBtn variant="text" block @click.stop="fileData.splice(index, 1)">
                            删除
                          </VBtn>
                        </VCardActions>
                      </VCard>
                    </VCol>
                  </template>
                </VRow>
              </div>
            </div>
          </div>
        </div>
        <VBtn variant="tonal" size="small" @click="open">
          浏览文件
        </VBtn>
      </VCardItem>
      <VCardItem>
        <!-- <v-card-text>
          <v-text-field label="标签" v-model="tags"></v-text-field>
        </v-card-text>
        <v-card-text>
          <v-text-field label="风格" v-model="style"></v-text-field>
        </v-card-text>
        <v-card-text>
          <v-text-field label="备注" v-model="remark"></v-text-field>
        </v-card-text> -->
        <v-card-text v-show="visibleCircle" style="display: flex;align-items: center;">
          <v-checkbox label="裁剪图片" v-model="cropImage"></v-checkbox>
          <VTooltip location="top">
            <template #activator="{ props }">
              <VIcon class="ml-2" v-bind="props" icon="tabler-info-circle " />
            </template>
            <span>输入裁剪边距</span>
          </VTooltip>
        </v-card-text>
        <v-card-text v-if="cropImage">
          <VRow>
            <VCol cols="3">
              <v-text-field label="边距左" v-model="cropLeft"></v-text-field>
            </VCol>
            <VCol cols="3">
              <v-text-field label="边距上" v-model="cropTop"></v-text-field>
            </VCol>
            <VCol cols="3">
              <v-text-field label="边距右" v-model="cropRight"></v-text-field>
            </VCol>
            <VCol cols="3">
              <v-text-field label="边距下" v-model="cropBottom"></v-text-field>
            </VCol>
          </VRow>
        </v-card-text>
        <v-card-text v-show="visibleSku" style="display: flex;align-items: center;">
          <v-checkbox label="生成SKU" v-model="generateSku"></v-checkbox>
          <VTooltip location="top">
            <template #activator="{ props }">
              <VIcon class="ml-2" v-bind="props" icon="tabler-info-circle " />
            </template>
            <span>输入生成SKU所需要的信息</span>
          </VTooltip>
        </v-card-text>
        <v-card-text v-if="generateSku">
          <v-card-text>
            <AppSelect v-model="podCategoryId" placeholder="行业分类" :items="POD_CATEGORY_SELECT" clearable clear-icon="tabler-x" />
          </v-card-text>
          <v-card-text>
            <AppSelect v-model="sizes" multiple class="mb-4" placeholder="尺码" :items="SIZE_SELECT" clearable clear-icon="tabler-x" />
          </v-card-text>
        </v-card-text>
      </VCardItem>
      <template v-slot:actions>
        <v-btn variant="elevated" @click="uploadFile" v-loading="loading">上传</v-btn>
      </template>
    </VCard>
  </VDialog>
</template>


<script setup lang="ts">
import { useDropZone, useFileDialog, useObjectUrl } from "@vueuse/core";
import { ref, watch, getCurrentInstance } from "vue";
import { uploadGalleryImage } from "@/utils";
import { toast } from "vuetify-sonner";
import "vue3-treeselect/dist/vue3-treeselect.css";
import { getPodCategoryTenantSimple } from "@/utils";
import ZipIcon from "@/assets/images/icons/zip.png";
import RarIcon from "@/assets/images/icons/rar.png";

const visible = ref(false);
const visibleCircle = ref(true);
const visibleSku = ref(true);
const { proxy } = getCurrentInstance();

//定义emit
const emit = defineEmits(["visible", "upload"]);

const tags = ref("");
const style = ref("");
const remark = ref("");
const cropImage = ref(false);
const cropLeft = ref();
const cropTop = ref();
const cropRight = ref();
const cropBottom = ref();
const generateSku = ref(false);
const podCategoryId = ref();
const sizes = ref([]);

const loading = ref(false);

const podCategoryList = ref([]);
const POD_CATEGORY_SELECT = ref([]);
const SIZE_SELECT = ref([]);


getPodCategoryTenantSimple().then((categoryList) => {
  POD_CATEGORY_SELECT.value = categoryList.map((element) => {
    return {
      title: element.name,
      value: element.id,
    };
  });
  podCategoryList.value = categoryList;
  podCategoryId.value = POD_CATEGORY_SELECT.value[0].value;
  // 默认选中第一个
});

watch(podCategoryId, () => {
  // 重置
  SIZE_SELECT.value = [];
  if (!podCategoryId.value) {
    return;
  }
  podCategoryList.value.filter((element) => {
    if (element.id == podCategoryId.value) {
      SIZE_SELECT.value = element.sizes.split(",").map((value) => {
        return {
          title: value,
          value: value,
        };
      });
    }
  });
});

async function uploadFile(fileObject) {
  loading.value = true;
  const formData = new FormData();
  fileData.value.forEach((file) => {
    formData.append("files", file.file);
  });
  formData.append("tags", tags.value);
  formData.append("style", style.value);
  formData.append("remark", remark.value);
  if (cropImage.value) {
    formData.append("cropLeft", cropLeft.value??0);
    formData.append("cropTop", cropTop.value??0);
    formData.append("cropRight", cropRight.value??0);
    formData.append("cropBottom", cropBottom.value??0);
  }
  formData.append("generateSku", generateSku.value);
  if (generateSku.value) {
    formData.append("podCategoryId", podCategoryId.value);
    formData.append("sizes", sizes.value.join(","));
  }
  const res = await uploadGalleryImage(formData).finally(() => {
    loading.value = false;
  });
  const hasRarOrZip = fileData.value.some(file => file.file.name.endsWith('.rar') || file.file.name.endsWith('.zip'));
  if (hasRarOrZip) {
    proxy.$toast.notification('上传任务', `本次上传包含压缩文档,新增上传任务`,'bottom-right')
  }else{
    proxy.$toast.success("上传成功");
  }
  emit("visible");
  emit("upload", res.data);
  visible.value = false;
}

const dropZoneRef = ref<HTMLDivElement>();
interface FileData {
  file: File;
  url: string;
}

const fileData = ref<FileData[]>([]);

const fileMime = ["image/png","application/zip","application/zip-compressed","application/x-zip-compressed"]

const { open, onChange,reset } = useFileDialog({
  accept: fileMime.join(","),
  reset: true
});

function onDrop(DroppedFiles: File[] | null) {
  DroppedFiles?.forEach((file) => {
    console.log(file);
    if (
      !(fileMime.includes(file.type))&&
      !file.name.endsWith(".rar")
    ) {
      // eslint-disable-next-line no-alert
      proxy.$dialog.alert('系统提示','仅支持上传PNG图片以及zip文件或者rar文件')
      return;
    }

    fileData.value.push({
      file,
      url: useObjectUrl(file).value ?? "",
    });
  });
}

onChange((selectedFiles: any) => {
  console.log('select',selectedFiles);
  if (!selectedFiles) return;

  for (const file of selectedFiles) {
    fileData.value.push({
      file,
      url: useObjectUrl(file).value ?? "",
    });
  }
});

watch(
  () => visible.value,
  () => {
    emit("visible");
    reset();
    fileData.value = [];
    tags.value = "";
    style.value = "";
    remark.value = "";
    cropImage.value = false;
    cropLeft.value = null;
    cropTop.value = null;
    cropRight.value = null;
    cropBottom.value = null;
    generateSku.value = false;
    podCategoryId.value = null;
    sizes.value = [];
  }
);

useDropZone(dropZoneRef, onDrop);

defineExpose({
  visible,
  visibleCircle,
  visibleSku
});
</script>

<style lang="scss" scoped>
.drop-zone {
  border: 1px dashed rgba(var(--v-theme-on-surface), var(--v-border-opacity));
}
</style>
